import { Args, Int, Mutation, Query, Resolver } from '@nestjs/graphql';
import { CREATE_POWER, DELETE_POWER, GqlAuthGuard, GqlCurrentUser, MakeGqlAuthPowerGuard, UPDATE_POWER, VIEW_POWER } from 'src/auth/auth.guard';
import { SystemMenuPath } from '../system.resolver';
import { PrismaService } from '@app/prisma';
import { UserPagination } from '@app/prisma/pagination/user.pagination/user.pagination';
import { UseGuards } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { SysUserEntity } from '@app/prisma/sys.user.entity/sys.user.entity';
import { UserService } from './user.service';
import { SysUserPowerEntity } from '@app/prisma/sys.user-power.entity/sys.user-power.entity';
import { UserPowerPagination } from '@app/prisma/pagination/user.power.pagination/user.power.pagination';


const UserGuard = MakeGqlAuthPowerGuard("/system/users", "用户管理", SystemMenuPath)
@Resolver()
export class UserResolver {
  constructor(
    private readonly prisma: PrismaService,
    private readonly service: UserService
  ) { }

  /**
   * 查询用户列表。
   */
  @Query(() => UserPagination)
  @UseGuards(UserGuard([VIEW_POWER]))
  async findUsers(
    @Args("page", { type: () => Int }) page: number,
    @Args("size", { type: () => Int }) size: number,
    @Args("id", { type: () => Int, nullable: true }) id?: number,
    @Args("account", { nullable: true }) account?: string,
    @Args("name", { nullable: true }) name?: string,
    @Args("sys_roleId", { nullable: true, type: () => Int }) sys_roleId?: number
  ) {
    const where: Prisma.sys_userWhereInput = {};
    if (!!account) {
      where.account = account
    }
    if (!!name) {
      where.name = {
        contains: name
      }
    }
    if (!!sys_roleId) {
      where.sys_roleId = sys_roleId
    }
    const total = await this.prisma.sys_user.count({ where });
    const data = await this.prisma.sys_user.findMany({
      skip: (page - 1) * size,
      take: size,
      where
    });
    return {
      total,
      page,
      size,
      data
    }
  }

  /**
   * 创建用户
   */
  @Mutation(() => SysUserEntity)
  @UseGuards(UserGuard([CREATE_POWER]))
  createUser(
    @Args("name") name: string,
    @Args("account") account: string,
    @Args("password") password: string,
    @Args("isOrgan", { type: () => Boolean }) isOrgan: boolean,
    @Args("sys_roleId", { nullable: true, type: () => Int }) sys_roleId?: number,
    @Args("province", { nullable: true }) province?: string,
    @Args("city", { nullable: true }) city?: string,
    @Args("email", { nullable: true }) email?: string,
  ) {
    return this.service.createUser({
      account,
      name,
      password,
      isOrgan: false,
      sys_roleId,
      province: "",
      city: "",
      email: "",
    })
  }

  /**
   * 修改用户信息
   */
  @Mutation(() => SysUserEntity)
  @UseGuards(UserGuard([UPDATE_POWER]))
  async updateUser(
    @Args("id", { type: () => Int }) id: number,
    @Args("account", { nullable: true }) account?: string,
    @Args("password", { nullable: true }) password?: string,
    @Args("name", { nullable: true }) name?: string,
    @Args("sys_roleId", { nullable: true, type: () => Int }) sys_roleId?: number
  ) {
    return this.service.updateUser(id, {
      account,
      password,
      name,
      sys_roleId
    })
  }

  /**
   * 删除用户
   */
  @Mutation(() => SysUserEntity)
  @UseGuards(UserGuard([DELETE_POWER]))
  deleteUser(@Args("id", { type: () => Int }) id: number) {
    return this.service.deleteUser(id)
  }

  //管理员添加权限
  @Mutation(() => SysUserPowerEntity)
  @UseGuards(UserGuard([CREATE_POWER]))
  async addPower(
    @Args("sys_test_chapterId", { type: () => Int }) sys_test_chapterId: number,
    @Args("end_time") end_time: string,
    @Args("sys_userId", { type: () => Int }) sys_userId: number,
  ) {
    return await this.prisma.sys_user_power.create({
      data: {
        sys_test_chapter: {
          connect: {
            id: sys_test_chapterId
          }
        },
        end_time,
        sys_user: {
          connect: {
            id: sys_userId
          }
        }
      }
    })
  }

  //管理员删除权限
  @Mutation(() => SysUserPowerEntity)
  @UseGuards(UserGuard([DELETE_POWER]))
  async removePower(
    @Args("id", { type: () => Int }) id: number,
  ) {
    return await this.prisma.sys_user_power.delete({
      where: {
        id
      }
    })
  }

  //用户获取权限表
  @Query(() => [SysUserPowerEntity])
  @UseGuards(GqlAuthGuard)
  async queryPowers(
    @GqlCurrentUser() user: SysUserEntity
  ) {
    return await this.prisma.sys_user_power.findMany({
      where: {
        sys_userId: user.id
      }
    })
  }


  //管理员获取权限表
  @Query(() => [SysUserPowerEntity])
  @UseGuards(UserGuard([VIEW_POWER]))
  async queryUserPowers(
    @Args("id", { type: () => Int }) id: number,
  ) {
    return await this.prisma.sys_user_power.findMany({
      where: {
        sys_userId: id
      }
    })
  }

  @Query(() => UserPowerPagination)
  @UseGuards(UserGuard([VIEW_POWER]))
  async queryUserPowerPagination(
    @Args("page", { type: () => Int, nullable: true }) page: number = 1,
    @Args("size", { type: () => Int, nullable: true }) size: number = 10,
    @Args("userId", { type: () => Int, nullable: true }) userId?: number,
    @Args("chapterId", { type: () => Int, nullable: true }) chapterId?: number
  ) {
    const where: Prisma.sys_user_powerWhereInput = {};
    if (!!userId) {
      where.sys_userId = userId
    }
    if (!!chapterId) {
      where.sys_test_chapterId = chapterId
    }
    const total = await this.prisma.sys_user_power.count({ where });
    const data = await this.prisma.sys_user_power.findMany({
      skip: (page - 1) * size,
      take: size,
      where,
      include: {
        sys_test_chapter: {
          include: {
            test: true
          }
        },
        sys_user: true
      }
    });
    return {
      total,
      page,
      size,
      data
    }
  }
}
